package cn.wolfcode.trip.web.controller;

import cn.wolfcode.trip.base.domain.Goods;
import cn.wolfcode.trip.base.domain.GoodsType;
import cn.wolfcode.trip.base.query.GoodsQueryObject;
import cn.wolfcode.trip.base.service.IGoodsService;
import cn.wolfcode.trip.base.service.IGoodsTypeService;
import cn.wolfcode.trip.base.util.JSONResult;
import cn.wolfcode.trip.base.util.QiniuCloudUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IGoodsTypeService goodsTypeService;


    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") GoodsQueryObject qo) {
        PageInfo<Goods> pageInfo = goodsService.selectForList(qo);
        model.addAttribute("result", pageInfo);
        model.addAttribute("types", goodsTypeService.listForState(GoodsType.TYPE_OPEN));
        return "goods/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(Long id) {
        JSONResult result = new JSONResult();
        goodsService.delete(id);
        return result;
    }

    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Goods goods, MultipartFile img) {
        if (img != null && img.getContentType().startsWith("image") && img.getSize() > 0) {
            String url = QiniuCloudUtil.uploadQiniu(img);
            goods.setCoverUrl(url);
        }
        goodsService.saveOrUpdate(goods);
        return "redirect:/goods/list.do";
    }

}
